package com.pw.study.flink.chapter;

import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

import java.util.Arrays;

/**
 * 有界流
 */
public class WC_StreamBorder {
    public static void main(String[] args) throws Exception {
         mk1();
    }

    private static void mk1() throws Exception {
        // 1. 创建流式执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        // 2. 读取文件
        DataStreamSource<String> txt = env.readTextFile("data/file/words.txt");


        // 3. 转换数据格式
        //输入，输出
        SingleOutputStreamOperator<Tuple2<String, Long>> kv = txt.flatMap((String line, Collector<String> words) -> {
            String[] lines = line.split(" ");
            Arrays.stream(lines).forEach(words::collect);
        }).returns(String.class).map(word -> Tuple2.of(word, 1L)).returns(Types.TUPLE(Types.STRING, Types.LONG));


        // 4. 分组
        KeyedStream<Tuple2<String, Long>, String> gv = kv.keyBy(t -> t.f0);
        // 5. 求和
        SingleOutputStreamOperator<Tuple2<String, Long>> sk = gv.sum(1);
        // 6. 打印
        sk.print();
        // 7. 执行
        env.execute();


    }

}
